<template>
  <div class="chat-container">
    <van-nav-bar title="聊天" left-arrow @click-left="goBack" />

    <div class="chat-list" ref="chatListRef">
      <div
        v-for="(msg, index) in state.messages"
        :key="index"
        :class="['chat-item', msg.isSelf ? 'self' : 'other']"
      >
        <img
          class="avatar"
          :src="msg.isSelf ? selfAvatar : otherAvatar"
          alt="avatar"
        />
        <div class="bubble">{{ msg.text }}</div>
      </div>
    </div>

    <div class="chat-input-bar">
      <van-field
        v-model="state.userMessage"
        placeholder="请输入消息"
        @keydown.enter="sendMessage"
        border="round"
        clearable
      />
      <van-button type="primary" @click="sendMessage" size="small">发送</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as signalR from '@microsoft/signalr'
import { useRouter, useRoute } from 'vue-router'
import { useCounterStore } from '@/stores/counter';
const store = useCounterStore();
const router = useRouter()
const route = useRoute()

// 假设通过路由参数传递对方用户名
const myId = store.useStore.mId|| 'patient1'
const otherId = route.query.otherId as string || 'doctor1'

const selfAvatar = 'https://img.yzcdn.cn/vant/cat.jpeg'
const otherAvatar = 'https://img.yzcdn.cn/vant/user-active.png'

const state = reactive({
  userMessage: '',
  messages: [] as { text: string; isSelf: boolean }[]
})

let connection: signalR.HubConnection
const chatListRef = ref<HTMLElement | null>(null)

const goBack = () => router.back()

const scrollToBottom = () => {
  nextTick(() => {
    if (chatListRef.value) {
      chatListRef.value.scrollTop = chatListRef.value.scrollHeight
    }
  })
}

const sendMessage = async () => {
  if (!state.userMessage.trim()) return
  // 发送私聊消息
  await connection.invoke('SendPrivateMessage', otherId, state.userMessage)
  state.messages.push({ text: state.userMessage, isSelf: true })
  state.userMessage = ''
  scrollToBottom()
}

onMounted(async () => {
  const options = { skipNegotiation: true, transport: signalR.HttpTransportType.WebSockets }
  connection = new signalR.HubConnectionBuilder()
    .withUrl('https://localhost:7064/ChatHub', options)
    .withAutomaticReconnect()
    .build()

  await connection.start()
  // 注册当前用户
  await connection.invoke('Register', myId)

  // 接收消息
  connection.on('ReceiveMessage', (msg: string) => {
    // 判断消息是否自己发的（可根据后端格式优化）
    // 这里假设msg格式为 "fromUser 时间: 内容"
    // 如果fromUser是自己，则不push（因为自己发的已在本地push），否则push为对方消息
    if (!msg.startsWith(myId + ' ')) {
      // 去掉前缀，只显示内容
      const text = msg.replace(/^.*?:\s*/, '')
      state.messages.push({ text, isSelf: false })
      scrollToBottom()
    }
  })
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f7f8fa;
}
.chat-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  background: #f7f8fa;
}
.chat-item {
  display: flex;
  align-items: flex-end;
  margin-bottom: 12px;
}
.chat-item.self {
  flex-direction: row-reverse;
}
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin: 0 8px;
}
.bubble {
  max-width: 65vw;
  padding: 10px 16px;
  border-radius: 18px;
  font-size: 15px;
  line-height: 1.5;
  background: #fff;
  color: #222;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.03);
  word-break: break-all;
}
.chat-item.self .bubble {
  background: #1989fa;
  color: #fff;
}
.chat-input-bar {
  display: flex;
  align-items: center;
  padding: 8px;
  background: #fff;
  border-top: 1px solid #eee;
}
:deep(.van-field) {
  flex: 1;
  margin-right: 8px;
}
</style>